'use strict';
const Service = require('egg').Service;
class ArticleService extends Service {

  // 列表
  async list(page = 1, pageSize = 10) {
    const { ctx } = this;
    const offset = parseInt((page - 1) * pageSize);
    const list = await ctx.model.Article.findAndCountAll({
      orders: [
        [ 'id', 'desc' ],
      ],
      limit: parseInt(pageSize),
      offset,
    });
    return {
      list,
    };
  }

  // 根据栏目id查找
  async findCid(cid, page = 1, pageSize = 10) {
    const { ctx } = this;
    const offset = parseInt((page - 1) * pageSize);
    const list = await ctx.model.Article.findAndCountAll({
      orders: [
        [ 'id', 'desc' ],
      ],
      where: {
        category_id: cid,
      },
      limit: parseInt(pageSize),
      offset,
    });
    return list;
  }

  // 详情
  async findId(id) {
    const { ctx } = this;
    const data = await ctx.model.Article.findOne({
      where: {
        id,
      },
    });
    return data;
  }

  // 删
  async delete(id) {
    const { ctx } = this;
    const result = await ctx.model.Article.destroy({
      where: {
        id,
      },
    });
    return result ? 'success' : 'fail';
  }

  // 创建
  async create(body) {
    const { ctx } = this;
    const result = await ctx.model.Article.create(body);
    return result ? 'success' : 'fail';
  }

  // 更新
  async update({
    id,
    title,
    cover,
    short_title,
    description,
    keyword,
    created_at,
    update_at,
    owner,
    visited,
    star,
    content,
    category_id,
    is_recomm,
    is_hot,
    is_tou,
  }) {
    const { ctx } = this;
    const result = await ctx.model.Article.update({
      id,
      title,
      cover,
      short_title,
      description,
      keyword,
      created_at,
      update_at,
      owner,
      visited,
      star,
      content,
      category_id,
      is_recomm,
      is_hot,
      is_tou,
    }, {
      where: {
        id,
      },
    });
    return result ? 'success' : 'fail';
  }
}

module.exports = ArticleService;
